package cn.kbblog.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.beetl.ext.servlet.ServletGroupTemplate;

import com.alibaba.fastjson.JSON;

import cn.kbblog.util.PropertiesUtil;

/**
 * 全局异常捕获处理
 *
 */
@WebServlet("/error")
public class ErrorHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ErrorHandler() {
		super();
	}

	@SuppressWarnings("rawtypes")
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 获取异常信息
		Class exceptionType = (Class) request.getAttribute("javax.servlet.error.exception_type");
		Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
		String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");


		Map<String, Object> error = new HashMap<>();
		if (statusCode != null)
			error.put("code", statusCode);
		if (exception != null)
			error.put("msg", exception.getMessage());
		if (exceptionType != null)
			error.put("exception", exceptionType.getName());
		if (servletName != null)
			error.put("servlet", servletName);
		if (requestUri != null)
			error.put("uri", requestUri);

		response.setStatus(200);//防止部分浏览器不显示自己的错误页面，强制将code设置为200
		//如果是ajax则返回json，如果是正常请求则返回错误页面
		if(requestUri!=null&&requestUri.indexOf("/ajax/")==0){
			response.setContentType("text/html");
			response.setHeader("Content-Type", "application/json;charset=utf-8");
			response.setHeader("Content-Encoding", "UTF-8");
			PrintWriter out = response.getWriter();
			error.put("err", 1);
			if(error.get("msg") == null) error.put("msg", "请求出现错误");
			out.print(JSON.toJSONString(error));
			out.flush();
			out.close();
		}else{
			request.setAttribute("error", error);
			ServletGroupTemplate.instance().render(PropertiesUtil.getProps("errropage"), request, response);
		}
	}

}
